/* eslint @typescript-eslint/no-unused-vars:off, no-unused-vars:off */
/*
 * 此文件封装的函数仅用于跟移动端交互
 * 统一引入方式：import { 函数名 } from '@utils/NativeUtils';
 * 描述：需要使用到此文件中的方法才需要引入此js文件
 * */

const u = navigator.userAgent;
const isWeiXin = !!/MicroMessenger/i.test(u);
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; // android终端
const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端

const printException = (func) => {
    if (!isWeiXin && !isAndroid && !isiOS) {
        console.error('非客户端环境，无法调用');
        return false;
    }
    try {
        func();
        return true;
    } catch (e) {
        console.error('非客户端环境，无法调用');
        return false;
    }
};

const waitAppCallback = (androidFuncName, iosFuncName, iosCallbackName) => {
    return new Promise((resolve, reject) => {
        try {
            if (isAndroid) {
                resolve(window.Android[androidFuncName]());
            } else if (isiOS && window.webkit && window.webkit.messageHandlers) {
                window[iosCallbackName] = (appArgs) => {
                    resolve(appArgs);
                };
                window.webkit.messageHandlers[iosFuncName].postMessage('');
            } else {
                console.error('非客户端环境，无法调用');
                reject();
            }
        } catch (e) {
            console.error(e);
            reject(e);
        }
    });
};

/**
 * @author: 邓子强
 * @Date: 2020/5/14
 * @function closeWebview 关闭Webview
 */
export function closeWebview() {
    return printException(() => {
        if (isAndroid) {
            window.Android.closeWebView();
        }
        if (isiOS) {
            window.webkit.messageHandlers.closeWebView.postMessage({});
        }
    });
}

/**
 * @author: 邓子强
 * @Date: 2021/8/02
 * @function closeWebview 关闭Webview
 */
export function openWebview(url, mode = 'NORMAL_MODE') {
    return printException(() => {
        if (isAndroid) {
            window.Android.openWebView(mode, url);
        }
        if (isiOS) {
            window.webkit.messageHandlers.openWebView.postMessage({ type: mode, url });
        }
    });
}

/**
 * @author: 邓子强
 * @Date: 2020/5/14
 * @function goGoldShop 前往金币商城
 */
export function goGoldShop() {
    printException(() => {
        if (isAndroid) {
            window.Android.goGoldShop();
        }
        if (isiOS) {
            window.webkit.messageHandlers.goGoldShop.postMessage('');
        }
    });
}

/**
 * @function goRoom 前往直播间
 * @author: 邓子强
 * @Date: 2020/7/27
 * @param roomId 房间Id
 */
export function goRoom(roomId) {
    printException(() => {
        if (isAndroid) {
            window.Android.openActivity('room', roomId);
        }
        if (isiOS) {
            window.webkit.messageHandlers.goLiveRoom.postMessage({
                roomId,
            });
        }
    });
}

/**
 * @function chatWithUser 打开私聊页
 * @author: 邓子强
 * @Date: 2021/7/5
 * @param displayUserId 用户Id
 */
export function chatWithUser(displayUserId) {
    printException(() => {
        if (isAndroid) {
            window.Android.openActivity('chat', `displayUserId=${displayUserId}`);
        }
        if (isiOS) {
            window.webkit.messageHandlers.chatWithUser.postMessage({
                displayUserId,
            });
        }
    });
}

/**
 * @param data base64或url
 */
export function saveImage(data) {
    return printException(() => {
        if (isAndroid) {
            window.Android.saveImage(data);
        }
        if (isiOS) {
            window.webkit.messageHandlers.saveImage.postMessage({
                data,
            });
        }
    });
}

/**
 * @function openPersonageInfo 打开个人资料页
 * @author: 邓子强
 * @Date: 2020/9/1
 * @param userId 用户ID
 */
export function openPersonageInfo(userId) {
    printException(() => {
        if (userId) {
            if (isAndroid) {
                window.Android.openActivity('personageInfo', `userId=${userId}`);
            }
            if (isiOS) {
                window.webkit.messageHandlers.openPersonageInfo.postMessage({
                    data: {
                        userId,
                    },
                });
            }
        }
    });
}

/**
 * @function goTaskPage 前往任务页
 * @author: 邓子强
 * @Date: 2020/8/5
 * @param taskTabIndex 任务页的tab索引0
 */
export const goTaskPage = (taskTabIndex = 0) => {
    printException(() => {
        if (isAndroid) {
            window.Android.openActivity('task', `${taskTabIndex}`);
        }
        if (isiOS) {
            window.webkit.messageHandlers.onNativeAction.postMessage({
                actionName: 'SLTaskViewController',
                data: `${taskTabIndex}`,
            });
        }
    });
};

/**
 * @function sendWaresToFriend 赠送商品给他人
 * @author: 邓子强
 * @Date: 2020/8/20
 */
export const sendWaresToFriend = (product) => {
    printException(() => {
        if (isAndroid) {
            window.Android.giveToFriend(JSON.stringify(product));
        }
        if (isiOS) {
            window.webkit.messageHandlers.giveToFriend.postMessage({
                data: JSON.stringify(product),
            });
        }
    });
};

/**
 * @function onPreviewWares 预览商品
 * @author: 邓子强
 * @Date: 2020/8/20
 */
export const onPreviewWares = (productTypeId, wares) => {
    printException(() => {
        if (isAndroid) {
            window.Android.showDialog(productTypeId, JSON.stringify(wares));
        }
        if (isiOS) {
            window.webkit.messageHandlers.handlePreviewWares.postMessage({
                data: Object.assign(wares, {
                    category: productTypeId,
                }),
            });
        }
    });
};

/**
 * @function getKumianmeiToken 获取token
 * @author: 邓子强
 * @Date: 2020/9/16
 */
export const getKumianmeiToken = () => {
    return waitAppCallback('getKumianmeiToken', 'getKumianmeiToken', 'getKumianmeiTokenCallback');
};

/**
 * @function getAppEnvironment 获取app所在的环境
 * @author: 邓子强
 * @Date: 2020/9/16
 * @return Promise 返回一个Promise,携带客户端返回的参数
 */
export const getAppEnvironment = (vm, successFn, failedFn) => {
    if (vm && vm.auth === 'dzq') {
        return new Promise((resolve) => {
            successFn();
            resolve('Kumianmei');
        });
    }
    return waitAppCallback('getAppEnvironment', 'getAppEnvironment', 'getAppEnvironmentCallback')
        .then(successFn)
        .catch(failedFn);
};

/**
 * @function getAppVersion 获取当前客户端的版本
 * @author: 邓子强
 * @Date: 2021/05/15
 * @return Promise 返回一个Promise,携带客户端返回的参数
 */
export const getAppVersion = () => {
    return waitAppCallback('getAppVersion', 'getAppVersion', 'getAppVersionCallback');
};

/**
 * @function BuyInApp app内购
 * @author: 邓子强
 * @Date: 2020/10/23
 * @param productId 商品ID
 */
export const BuyInApp = (productId = '') => {
    printException(() => {
        if (isAndroid) {
            window.Android.openActivity('wealth', productId);
        }
        if (isiOS) {
            window.webkit.messageHandlers.BuyInApp.postMessage({
                data: { productId },
            });
        }
    });
};

/**
 * @function popupTribeIntro 打开部落介绍弹窗
 * @author: 邓子强
 * @Date: 2020/11/20
 */
export const popupTribeIntro = () => {
    printException(() => {
        if (isAndroid) {
            window.Android.openActivity('tribeDialog', '');
        }
        if (isiOS) {
            window.webkit.messageHandlers.onNativeAction.postMessage({
                actionName: 'SLTribeListView',
                data: '',
            });
        }
    });
};

/**
 * @function jumpTribe 跳到部落Tab
 * @author: 邓子强
 * @Date: 2020/11/20
 */
export const jumpTribe = () => {
    printException(() => {
        if (isAndroid) {
            window.Android.routeAppView('Kumianmei://App/Tribe');
        }
        if (isiOS) {
            window.webkit.messageHandlers.jumpTribe.postMessage({
                data: '',
            });
        }
    });
};

/**
 * @function openSharePanel 弹出分享面板
 * @author: 邓子强
 * @Date: 2020/11/21
 * @param id 自定义的唯一表示
 * @param type 打开webview的类型 [FULL_MODE,MINI_MODE,NORMAL_MODE]
 * @param shareUrl 当前分享页的地址
 * @param {object} customData 自定义分享的数据
 * @param {object} customDataKey 自定义分享的data的key值
 * @param {object} topLevelData 拓展分享给客户端的Data
 */
export const openSharePanel = (
    id,
    type,
    shareUrl,
    topLevelData = {},
    customData = {},
    customDataKey = 'h5Data'
) => {
    return printException(() => {
        if (isAndroid) {
            window.Android.openSharePanel(
                JSON.stringify({
                    type: id,
                    uri: `Kumianmei://home/web?urlType=2&windowType=${type}&url=${shareUrl}`,
                    [customDataKey]:
                        typeof customData === 'string' ? customData : JSON.stringify(customData),
                    ...topLevelData,
                })
            );
        }
        if (isiOS) {
            window.webkit.messageHandlers.openSharePanel.postMessage({
                data: {
                    type: id,
                    uri: `Kumianmei://home/web?urlType=2&windowType=${type}&url=${shareUrl}`,
                    [customDataKey]:
                        typeof customData === 'string' ? customData : JSON.stringify(customData),
                    ...topLevelData,
                },
            });
        }
    });
};

/**
 * @function handleShareCallback 客户端触发分享面板回调
 */
export const handleShareCallback = () => {
    return waitAppCallback(
        'handleShareCallback',
        'handleShareCallback',
        'handleShareCallbackCallBack'
    );
};

/**
 * @function goBeanPage 去金豆账户页面
 * @author: 邓子强
 * @Date: 2020/12/10
 */
export const goBeanPage = () => {
    printException(() => {
        if (isAndroid) {
            window.Android.openActivity('BeanExport', '');
        }
        if (isiOS) {
            window.webkit.messageHandlers.onNativeAction.postMessage({
                actionName: 'BeanExport',
                data: '',
            });
        }
    });
};

/**
 * @function openGiftPanel 弹出分享面板
 * @author: 邓子强
 * @Date: 2021/03/04
 */
export const openGiftPanel = () => {
    printException(() => {
        if (isAndroid) {
            window.Android.showSendGiftDialog();
        }
        if (isiOS) {
            window.webkit.messageHandlers.openGiftPanel.postMessage({});
        }
    });
};

/**
 * @function getCurrentRoomInfo 获取当前房间信息
 * @author: 邓子强
 * @Date: 2021/03/05
 */
export const getCurrentRoomInfo = () => {
    return waitAppCallback(
        'getKumianmeiRoomInfo',
        'getKumianmeiLiveId',
        'getKumianmeiLiveIdCallback'
    );
};

/**
 * @function userPermissionDenied 提示用户权限不足
 * @author: 邓子强
 * @Date: 2021/4/2
 */
export function userPermissionDenied() {
    return printException(() => {
        if (isAndroid) {
            window.Android.userPermissionDenied();
        }
        if (isiOS) {
            window.webkit.messageHandlers.userPermissionDenied.postMessage({});
        }
    });
}

/**
 * @function onNativeAction 打开原生界面
 * @author: 邓子强
 * @Date: 2021/4/19
 * @param actionName 事件名称
 * @param data 事件
 */
export function onNativeAction(actionName, data = '') {
    printException(() => {
        if (isAndroid) {
            window.Android.openActivity(actionName, data);
        }
        if (isiOS) {
            window.webkit.messageHandlers.onNativeAction.postMessage({
                actionName,
                data,
            });
        }
    });
}

/**
 * @function openGroupById 打开群组
 * @author: 邓子强
 * @Date: 2021/4/19
 * @param groupId 说明
 */
export function openGroupById(groupId) {
    printException(() => {
        if (isiOS) {
            window.webkit.messageHandlers.onNativeAction.postMessage({
                actionName: 'SLGroupChatScene',
                data: JSON.stringify({ groupId }),
            });
        }
    });
}

/**
 * @function openMessageView 打开会话面板
 * @author: 邓子强
 * @Date: 2021/9/17
 */
export function openMessageView() {
    return printException(() => {
        if (isAndroid) {
            window.Android.openActivity('messagePopups', '');
        }
        if (isiOS) {
            window.webkit.messageHandlers.onNativeAction.postMessage({
                actionName: 'SLMessageController',
            });
        }
    });
}

/**
 * @function openGameOperaPanel 打开悬浮在第三方游戏上的操作面板
 * @author: 邓子强
 * @Date: 2021/6/4
 */
export function openGameOperaPanel() {
    printException(() => {
        if (isAndroid) {
            window.Android.openGameOperaPanel();
        }
        if (isiOS) {
            window.webkit.messageHandlers.openGameOperaPanel.postMessage('');
        }
    });
}

export function closeGameOperaPanel() {
    printException(() => {
        if (isAndroid) {
            window.Android.closeGameOperaPanel();
        }
        if (isiOS) {
            window.webkit.messageHandlers.closeGameOperaPanel.postMessage('');
        }
    });
}

/**
 * @function 打开客户端的上传控件
 * @author: 邓子强
 * @Date: 2021/7/1
 * @return {Promise}
 */
export const uploadInApp = (fn) => {
    return new Promise((resolve, reject) => {
        try {
            window.feedbackPictureUrl = (appArgs) => {
                fn?.(appArgs);
                resolve(appArgs);
            };
            if (isAndroid) {
                window.Android.choosePicture();
            } else if (isiOS) {
                window.webkit.messageHandlers.feedbackPictureUrl.postMessage('');
            } else {
                reject();
            }
        } catch (e) {
            console.error('非客户端环境，无法调用');
            reject(e);
        }
    }).catch((e) => {
        console.error('非客户端环境，无法调用: uploadInApp', e);
    });
};

/**
 * @function joinedTribe 加入部落
 * @author: 邓子强
 * @Date: 2021/7/7
 */
export const joinedTribe = () => {
    try {
        if (isAndroid) {
            window.Android.joinTribeSuccess();
        }
    } catch (e) {
        console.error('非客户端环境，无法调用');
    }
};

export const routeAppView = (link) => {
    return printException(() => {
        if (isAndroid) {
            window.Android.routeAppView(link);
        }
        if (isiOS) {
            window.webkit.messageHandlers.routeAppView.postMessage({
                data: link,
            });
        }
    });
};

/**
 * @function getDeviceId 获取设备ID
 * @author: 邓子强
 * @Date: 2021/12/15
 * @return Promise 返回一个Promise,携带客户端返回的参数
 */
export const getDeviceId = () => {
    return waitAppCallback('getDeviceId', 'getDeviceId', 'getDeviceIdCallback');
};

/**
 * @function batchSendMsg
 * @description 批量发送消息
 * @author: 邓子强
 * @Date: 2022/1/19
 * @param {Array} displayUserIds 用户ID列表
 * @param {String} message 消息内容
 */
export const batchSendMsg = (displayUserIds, message) => {
    return printException(() => {
        if (isAndroid) {
            window.Android.sendMessageToMore(JSON.stringify(displayUserIds), message);
        }
        if (isiOS) {
            window.webkit.messageHandlers.sendMessageToMore.postMessage({
                data: JSON.stringify({
                    displayUserIdList: displayUserIds,
                    message,
                }),
            });
        }
    });
};

/**
 * @function getAppPluginsData
 * @description 获取房间内缓存的数据
 * @author: 邓子强
 * @Date: 2022/02/18
 * @return Promise<T> 返回Promise
 */
export const getAppPluginsData = () => {
    return waitAppCallback('getAppPluginsData', 'getAppPluginsData', 'handleAppPluginsData');
};

/**
 * @function reportEventToApp
 * @description 发送埋点数据
 * @author: 邓子强
 * @Date: 2022/03/04
 * @param {String} key 埋点key name
 * @param data 埋入的数据
 */
export const reportEventToApp = (key, data) => {
    return printException(() => {
        if (isAndroid) {
            window.Android.reportDataToApp(key, data);
        }
        if (isiOS) {
            window.webkit.messageHandlers.reportDataToApp.postMessage({
                key,
                data,
            });
        }
    });
};

/**
 * @function openUri
 * @description 打开banner的链接
 * @author: 邓子强
 * @Date: 2022/02/18
 * @return Promise<T> 返回Promise
 */
export const openUri = (uri, mode = 'NORMAL_MODE') => {
    if (/([sS])ango:\/\/.*/.test(uri)) {
        routeAppView(uri);
    } else if (/^(http|www)/.test(uri)) {
        if (!openWebview(uri, mode)) {
            window.location.href = uri;
        }
    } else if (uri === 'App/Home/UserInfoMation' && window.localStorage.getItem('userInfo')) {
        const displayUserId =
            JSON.parse(window.localStorage.getItem('userInfo'))?.displayUserId || '';
        openPersonageInfo(displayUserId);
    } else {
        const [str, protocol, keyName, keyValue] = uri.match(/([a-zA-Z]*)\??([a-zA-Z]*)=?(.*)/);
        switch (protocol) {
            case 'room':
                goRoom(keyValue);
                break;
            case 'personageInfo':
                openPersonageInfo(keyValue);
                break;
            case 'group':
                openGroupById(keyValue);
                break;
            case 'ranking':
                jumpTribe(keyValue);
                break;
            case 'wealth':
                goGoldShop();
                break;
            case 'store':
                openWebview(`${window.location.origin}/to-h5/shop`, mode);
                break;
            case 'chat':
                chatWithUser(keyValue);
                break;
            case 'task':
                goTaskPage();
                break;
            default:
                openWebview(uri, mode);
                break;
        }
    }
};

/**
 * @function refreshGoldCoins 通知客户端刷新金币数量
 * @author: 罗昊恺
 * @Date: 2022/4/21
 */
export function refreshGoldCoins() {
    printException(() => {
        if (isAndroid) {
            window.Android.refreshGoldCoins();
        }
        if (isiOS) {
            window.webkit.messageHandlers.refreshGoldCoins.postMessage('');
        }
    });
}

//------------------------------------
/**
 * 上报埋点数据
 * @function reportPageView 上报访问页面
 */
const _env = import.meta.env.MODE ?? 'development';
const gtagId = 'G-XV7GMLEMS4';
const appVersion = window.sessionStorage.getItem('version') ?? '未知';
const appDeviceIdId = window.localStorage.getItem('deviceId') ?? '未知';
export const reportPageView = (
    pageTitle = 'Kumianmei',
    host = window.location.origin,
    path = window.location.pathname
) => {
    console.log(_env, '_env');
    try {
        if (_env === 'development') {
            window?.gtag?.('event', 'page_view', {
                page_title: pageTitle,
                page_location: host,
                page_path: path,
                send_to: gtagId,
            });
        } else {
            console.info(
                `%c埋点 path:[${path}] - pageTitle:${pageTitle}`,
                'color: #333;background-color: #85c6ff;'
            );
        }
    } catch (e) {
        console.log(e);
    }
};

// 上报埋点数据
/**
 * @function reportEvent
 * @description 上报事件埋点
 */
export const reportEvent = (category = '', action = '', label = '', reportUser = true) => {
    let displayUserId = '';
    if (window.localStorage.getItem('userInfo')) {
        displayUserId = JSON.parse(window.localStorage.getItem('userInfo')).displayUserId || '空';
    }
    const _label = `${label}${
        reportUser && `+用户ID:${displayUserId}`
    }+version:${appVersion}+deviceId:${appDeviceIdId}`;
    try {
        if (_env === 'production') {
            window?.gtag?.('event', category, {
                event_category: category,
                event_action: action,
                event_label: _label,
            });
        } else {
            console.table([`category:${category}`, `action:${action}`, `label:${_label}`]);
        }
    } catch (e) {
        console.log(e);
    }
};

export const reportScreenView = (screenName) => {
    try {
        if (_env === 'production') {
            window?.gtag?.('event', 'screen_view', {
                app_name: 'KumianmeiH5',
                screen_name: screenName,
                app_version: appVersion,
            });
        } else {
            console.table({
                app_name: 'KumianmeiH5',
                screen_name: screenName,
                app_version: appVersion,
            });
        }
    } catch (e) {
        console.log(e);
    }
};

/**
 * @function openSharePanel 跳转赏金猎人
 * @param id 自定义的唯一表示
 * @param type 打开webview的类型 [FULL_MODE,MINI_MODE,NORMAL_MODE]
 * @param sourceUrl 当前分享页的地址
 * @param clubId 部落id
 */
export const openBountyHunter = (id, sourceUrl, clubId = '', h5Data) => {
    printException(() => {
        if (isAndroid) {
            window.Android.openSharePanel(
                JSON.stringify({
                    type: id,
                    uri: sourceUrl,
                    clubId,
                    h5Data,
                })
            );
        }
        if (isiOS) {
            window.webkit.messageHandlers.openSharePanel.postMessage({
                data: {
                    type: id,
                    uri: sourceUrl,
                    clubId,
                    h5Data,
                },
            });
        }
    });
};

/**
 * @function iOS设置标题
 * @param title 标题
 */
export function setPageTitle(title) {
    printException(() => {
        if (title) {
            if (isAndroid) {
                window.Android.openActivity('setTitle', '');
            }
            if (isiOS) {
                window.webkit.messageHandlers.setTitle.postMessage(title);
            }
        }
    });
}
